package com.example.memento.download.util;

import com.example.memento.download.config.DownloadProperties;
import com.example.memento.download.service.DownloadService;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Profile;
import org.springframework.stereotype.Component;

import java.nio.file.Path;

/**
 * 命令行工具：下载 DomainWordsDict 到 data/res 目录
 * 使用方式: mvn spring-boot:run -Dspring-boot.run.arguments="--spring.profiles.active=download-domain-words"
 * 或者: java -jar target/memento-download-*.jar --spring.profiles.active=download-domain-words
 */
@Component
@Profile("download-domain-words")
public class DomainWordsDownloader {

    private static final String GITHUB_URL = "https://github.com/liuhuanyong/DomainWordsDict/archive/refs/heads/master.zip";
    private static final String TARGET_DIR = "data/res";

    @Bean
    public CommandLineRunner downloadDomainWords(DownloadService downloadService, DownloadProperties properties) {
        return args -> {
            System.out.println("开始下载 DomainWordsDict...");
            System.out.println("URL: " + GITHUB_URL);
            System.out.println("目标目录: " + TARGET_DIR);
            
            try {
                Path targetPath = Path.of(TARGET_DIR);
                var files = downloadService.downloadAll(
                    java.util.List.of(GITHUB_URL),
                    targetPath,
                    true  // 自动解压
                );
                
                System.out.println("下载完成！");
                System.out.println("保存的文件:");
                files.forEach(f -> System.out.println("  - " + f.toAbsolutePath()));
                System.out.println("解压位置: " + targetPath.toAbsolutePath());
            } catch (Exception e) {
                System.err.println("下载失败: " + e.getMessage());
                e.printStackTrace();
                System.exit(1);
            }
        };
    }
}

